package amqp

import (
	log "github.com/sirupsen/logrus"
	"github.com/streadway/amqp"
	"queue-gateway/config"
	"time"
)

var Dial *amqp.Connection

func init() {
	Dial, _ = amqp.Dial(config.App.RabbitMQ.Url)
	ProducersMustInit()
	ConsumerInit()
}

type Producer struct {
	Exchange string
	RouteKey string
	Channel  *amqp.Channel
}

func DialChannel() *amqp.Channel {
	Channel, err := Dial.Channel()
	if err != nil {
		panic(err)
	}
	return Channel
}

func NewProducer(exchange, routekey string) *Producer {
	log.Printf("new a producer: exchange:%s, routekey:%s", exchange, routekey)
	return &Producer{Exchange: exchange, RouteKey: routekey, Channel: DialChannel()}
}

// QueueDeclare 创建一个queue
func QueueDeclare(channel *amqp.Channel, name string) (*amqp.Queue, error) {

	declare, _ := channel.QueueDeclare(name, false, false, false, false, nil)

	return &declare, nil
}

func (p *Producer) Publish(message []byte, taskid string, headers map[string]interface{}) {
	err := p.Channel.Publish(p.Exchange, p.RouteKey, false, false, amqp.Publishing{
		Body:      message,
		Headers:   headers,
		Timestamp: time.Now(),
	})
	log.Printf("publish finish!, taskid:%s, headers:%v", taskid, headers)
	if err != nil {
		return
	}
}
